package cn.edu.zjgsu.ito.controller;
import cn.edu.zjgsu.ito.service.LoginService;
import cn.edu.zjgsu.ito.service.ServiceFactory;


import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;


public class LoginController extends Controller{
	/*
	 * 张虎涛
	 * 2016/06/01
	 */
	
	private LoginService loginService=ServiceFactory.createLoginService();
	
	private String username;
	
	private String password;
	
	private String character;
	
	//登录界面
	public void index()
	{
		getSession().invalidate();
		setSessionAttr("flag", "0");
		render("common/login/login.html");
		return;
	}
	//更改密码后登录界面
	public void upPass()
	{
		setAttr("message", "密码修改成功,请重新登陆");
		getSession().invalidate();
		setSessionAttr("flag", "0");
		render("common/login/login.html");
	}
	//错误操作
		public void toErrors()
		{
			render("common/errors/404.html");
		}
	
	//登录验证
	public void validate(){
		username=getPara("username");
		password=getPara("password");
		character=getPara("character");
		
		if(character==null)//防止没有选择用户类型
		{ 
			setAttr("message", "请选择用户类型");
			setSessionAttr("flag", "0");
			render("common/login/login.html");
			return;
		}else if(username==null ||password==null){
			setAttr("message", "用户名或密码不能为空");
			setSessionAttr("flag", "0");
			render("common/login/login.html");
			return;
		}else{
			if(character.equals("stu")){//登陆身份为学生
				
				Record r=loginService.validatorLoginStu(username, password);
				if(r!=null)
			       {
					//保存用户名，方便后续身份验证
					setSessionAttr("passportNo", r.get("passportNo"));
					setSessionAttr("flag","1");
					
					render("student/student.html");
					return;
			       }
				else{
			    	   
					setAttr("message", "用户名或密码错误!");
					setSessionAttr("flag", "0");
					 
					render("common/login/login.html");
					return;
				}
			}
			if(character.equals("tea")){//教师登录
				Record r=loginService.validatorLoginTea(username, password);
				if(r!=null)
			       {
					setSessionAttr("tNo", r.get("tNo"));
					setSessionAttr("flag", "1");
					render("teacher/teacher.html");
					return;
			       }
				else{			    	   
					setAttr("message", "用户名或密码错误!");
					setSessionAttr("flag", "0");
					 
					render("common/login/login.html");
					return;
				}
				
			}
			if(character.equals("admin")){//管理员登录
				Record r=loginService.validatorLoginAdmin(username, password);
				if(r!=null)
			       {
					setSessionAttr("aNo", r.get("aNo"));
					setSessionAttr("flag","1");
					render("admin/admin.html");
					return;
			       }
				else{
			    	   
					setAttr("message", "用户名或密码错误!");
					setSessionAttr("flag", "0");
					render("common/login/login.html");
					return;
				}
			}
		}
	}
}
